<template>
  <div class="page-wrapper">
    <div style="text-align: left; margin-bottom: 20px;">
      <back-btn @click="goBack" />
    </div>
    <c-box :title="name + ' - 数据列表'">
      <el-button slot="func" size="small" @click="showAddDlg">添加数据项</el-button>
      <el-table ref="table" v-loading="loading" :data="dataList" style="width: 100%" height="494">
        <el-table-column prop="variablename" label="数据名" />
        <!-- <el-table-column prop="variabletype" label="数据类型">
          <template v-slot="{row}">{{ getVarType(row.variabletype) }}</template>
        </el-table-column> -->
        <el-table-column prop="variabletype" label="数据类型" />
        <el-table-column prop="dctype" label="采集类型" />
        <el-table-column prop="ratio" label="转换系数" />
        <el-table-column prop="length" label="数据长度" />
        <el-table-column prop="datacodeid" label="数据编码" />
        <el-table-column prop="address" label="操作">
          <template slot-scope="{row}">
            <el-button type="text" size="small" @click="showEditDlg(row)">编辑</el-button>
            <el-button type="text" size="small" @click="deleteData(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          layout="prev, pager, next"
          :total="page.total"
          :current-page="page.index"
          :page-size="page.size"
          @current-change="pageChange"
        />
      </div>
    </c-box>
    <c-dialog
      v-if="newData"
      :visible.sync="showDlg"
      :title="(newData.pkid ? '编辑' : '添加')+'数据项'"
      @close="showDlg = false"
    >
      <el-form ref="form" :model="newData" :rules="rules" label-width="60px" label-position="top">
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="数据名:" prop="variablename">
              <el-input v-model="newData.variablename" size="small" placeholder="请输入" />
            </el-form-item>
          </div>
          <spliter />
          <div class="row-item">
            <el-form-item label="数据项数目:" prop="number">
              <el-input
                v-model="newData.number"
                :disabled="!!newData.pkid"
                size="small"
                :placeholder="newData.pkid ? '' : '请输入'"
              />
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="数据类别:" prop="variabletype">
              <el-cascader v-model="newData.variabletype" :options="varTypes" :show-all-levels="false" clearable></el-cascader>
            </el-form-item>
          </div>
          <spliter />
          <div class="row-item">
            <el-form-item label="数据编码:" prop="datacodeid">
              <el-select v-model="newData.datacodeid" size="small" placeholder="请输入">
                <el-option
                  v-for="item in varCodes"
                  :key="+item.no"
                  :label="item.name"
                  :value="+item.no"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="转换系数:" prop="ratio">
              <el-input v-model="newData.ratio" size="small" placeholder="请输入" />
            </el-form-item>
          </div>
          <spliter />
          <div class="row-item">
            <el-form-item label="数据长度:" prop="length">
              <el-select v-model="newData.length" size="small" placeholder="请输入">
                <el-option
                  v-for="item in varLens"
                  :key="item.no"
                  :label="item.name"
                  :value="item.no"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="采集类型:" prop="dctype">
              <el-select v-model="newData.dctype" size="small" placeholder="请输入">
                <el-option v-for="t in dctypes" :key="t.id" :value="t.name" :label="t.name"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <spliter />
          <div class="row-item"></div>
        </div>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="small" @click="saveData">确定</el-button>
        <el-button size="small" @click="showDlg = false">取消</el-button>
      </div>
    </c-dialog>
  </div>
</template>

<script>
import BackBtn from "@/components/BackBtn";
import CBox from "@/components/CCard";
import CDialog from "@/components/CDlg";
import Spliter from "@/components/Spliter";
import { clone } from "lodash";
import { delDataTmp } from "@/api/front";
import { calcPageNum } from "@/utils";
export default {
  components: {
    BackBtn,
    CDialog,
    CBox,
    Spliter
  },
  data() {
    return {
      id: null,
      loading: false,
      dataList: null,
      showDlg: false,
      name: "",
      page: {
        index: 1,
        size: 10,
        total: 0
      },
      newData: null,
      varTypes: [],
      varLens: null,
      varCodes: null,
      dctypes: null,
      rules: {
        variablename: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        usercode: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        emailaddress: [
          { type: "email", message: "邮箱地址格式不正确", trigger: "blur" }
        ],
        userType: [
          { required: true, message: "请选择用户类型", trigger: "blur" }
        ]
      }
    };
  },
  mounted() {
    const h = this.$refs["table"].$el.clientHeight;
    const n = calcPageNum(h);
    this.$set(this.page, "size", n);

    this.id = this.$route.params.id;
    this.name = this.$route.query.name;
    this._getVarTypes();
    this._getVarLens();
    this._getVarCodes();
    this._getDcType();
    this._getDataList();
  },
  methods: {
    goBack() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.back();
    },
    _getDataList() {
      this.loading = true;
      const params = {
        dataAreaid: this.id,
        rows: this.page.size,
        page: this.page.index
      };
      return this.$axios
        .get("fes/device/dataareaName", { params })
        .then(res => {
          if (res.code === 1) {
            this.$set(this.page, "total", res.data.total);
            this.dataList = res.data.rows;
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e))
        .finally(() => (this.loading = false));
    },
    _getVarTypes() {
      this.$axios
        .get("fes/drop/queryVrdatanew")
        .then(res => {
          if (res.code === 1) {
            // 获取联动数据
            this.varTypes = res.data;
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e));
    },
    _getVarLens() {
      this.$axios
        .get("fes/drop/queryProtocoltype?table=fes_datalength")
        .then(res => {
          if (res.code === 1) {
            this.varLens = res.data;
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e));
    },
    _getVarCodes() {
      this.$axios
        .get("fes/drop/queryProtocoltype?table=fes_datacodetype")
        .then(res => {
          if (res.code === 1) {
            this.varCodes = res.data;
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e));
    },
    getVarType(type) {
      if (!this.varTypes) return null;
      const a = this.varTypes.filter(e => e.variabletype === type)[0];
      return a && a.variablename;
    },
    _getDcType() {
      return this.$axios
        .get("fes/drop/queryDataacqtype")
        .then(res => {
          if (res.code === 1) {
            this.dctypes = res.data;
          } else {
            throw res.msg;
          }
        })
        .catch();
    },
    // 新增
    showAddDlg() {
      this.showDlg = true;
      if (!this.newData) {
        this.newData = { dataareaid: this.id };
      } else {
        this.newData.pkid && (this.newData = { dataareaid: this.id });
      }
    },
    // 编辑
    showEditDlg(data) {
      this.showDlg = true;
      this.newData = clone(data);
      // console.log("111", this.newData.variabletype)
    },
    pageChange(index) {
      this.$set(this.page, "index", index);
      this._getDataList();
    },
    saveData() {
      const variableData = this.newData.variabletype
      console.log('数据类型', typeof variableData === 'string')
      const load = this.$loading();
      const newData = {
        createTime: this.newData.createTime,
        dataareaid: this.newData.dataareaid,
        datacodeid: this.newData.datacodeid,
        deviceid: this.newData.deviceid,
        xuhao: this.newData.xuhao,
        variablename: this.newData.variablename,
        // variabletype: this.newData.variabletype[1],
        variabletype: (typeof variableData === 'string') ? variableData : variableData[1],
        ratio: this.newData.ratio,
        realType: this.newData.realType,
        length: this.newData.length,
        number: this.newData.number,
        updateTime: this.newData.updateTime,
        status: this.newData.status,
        pkid: this.newData.pkid,
        dctype: this.newData.dctype
      }
      console.log("提交数据", newData)
      return this.$axios
        .post("fes/device/dataareaTmpNameEdit", newData)
        .then(res => {
          if (res.code === 1) {
            this._getDataList();
            this.showDlg = false;
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e))
        .finally(() => load.close());
    },
    deleteData(r) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delDataTmp(r.pkid)
          .then(() => {
            this._getDataList();
          })
          .catch(e => this.$message.error(e));
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.row {
  display: flex;
  &.func {
    justify-content: center;
  }
  & > div,
  & > button {
    margin: 0 20px;
  }
}
</style>
